<template>
  <el-dialog
    :title="code == 'add' ? '新增文章' : '编辑文章'"
    width="80%"
    :visible.sync="isShow"
    @close="cancel"
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="封面" prop="img">
        <template>
          <upload-img
            :isShowTip="false"
            :limit="1"
            :value="form.img"
            @input="uploadImgBack($event)"
          />
        </template>
      </el-form-item>

      <el-form-item label="文章名" prop="title">
        <el-input
        size="mini"
          placeholder="请输入文章名"
          style="max-width: 720px;"
          type="textarea"
          v-model="form.title"
          maxlength="100"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="文章排序" prop="sort">
        <el-input
          placeholder="请输入文章排序"
          style="max-width: 220px;"
          v-model.number="form.sort"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章作者" prop="author">
        <el-input
          style="max-width: 220px;"
          placeholder="请输入作者"
          v-model.number="form.author"
        ></el-input>
      </el-form-item>
      <el-form-item label="发表时间" prop="publicationTime">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="form.publicationTime"
          type="datetime"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 400px; overflow-y: hidden"
            v-model="form.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="cancel()">取消</el-button>
        <el-button @click="submit()" type="primary">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
// 富文本
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { addNewArticle, updateArticle } from "@/api/article";
import uploadImg from "../../../components/uploadImg";

export default {
  name: "problemCom",
  components: { Editor, Toolbar, uploadImg },
  data() {
    return {
      code: "",
      isShow: false,
      form: {
        title: "",
        content: "",
        sort: "",
        author: "",
        publicationTime: "",
        img: "http://applet.atptest.com/RtTk5Oca1682497720771.png"
      },
      rules: {
        title: [
          {
            required: true,
            message: "必填",
            trigger: ["blur", "change"]
          }
        ],
        sort: [
          { required: true, message: "必填", trigger: ["blur", "change"] },
          {
            type: "number",
            message: "必须为数字值",
            trigger: ["blur", "change"]
          }
        ],
        author: [
          { required: true, message: "必填", trigger: ["blur", "change"] }
        ],
        publicationTime: [
          {
            required: true,
            message: "必填",
            trigger: ["blur", "change"]
          }
        ],
        content: [
          {
            required: true,
            message: "必填",
            trigger: ["blur", "change"]
          }
        ],
        img: [
          {
            required: true,
            message: "必填",
            trigger: ["blur", "change"]
          }
        ]
      },
      rowData: {},
      // 富文本
      editor: null,
      // 工具栏配置
      toolbarConfig: {},
      // editorConfig: { placeholder: "请输入内容..." },
      editorConfig: { MENU_CONF: {} },
      mode: "default" // or 'simple'
    };
  },
  methods: {
    // 上传图片的回调
    uploadImgBack(x) {
      if (x && x.length > 0) this.form.img = x[0].url;
    },

    // 新增
    add(v) {
      addNewArticle(v).then(res => {
        this.$message.success("新增成功");
        this.$emit("getProblem"); // 刷新父列表
        this.isShow = false;
      });
    },

    // 修改
    edit(v) {
      updateArticle(v).then(res => {
        this.$message.success("修改成功");
        this.$emit("getProblem"); // 刷新父列表
        this.isShow = false;
      });
    },

    // 取消提交
    cancel() {
      this.isShow = false;
      // 清空form
      this.$refs.form.resetFields();
      this.form = {
        title: "",
        content: "",
        sort: "",
        author: "",
        publicationTime: "",
        img:"http://applet.atptest.com/RtTk5Oca1682497720771.png"
      };
    },

    // 修改数据提交
    submit() {
      this.$refs.form.validate(result => {
        if (result) {
          if (this.code === "add") {
            this.form.author = this.form.author.toString();
            this.add(this.form);
          } else if (this.code === "edit") {
            delete this.form.updateTime;
            this.edit(this.form);
          }
        }
      });
    },
    // 富文本
    // 这一步是初始化 一定要写
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    }
  },
  created() {},
  mounted() {

    this.editorConfig.MENU_CONF["uploadImage"] = {
      server:
        "https://wechat.atptest.com:44387/api/PCApplet/UploadLargeFileOBS",

      // form-data fieldName ，默认值 'wangeditor-uploaded-image'
      fieldName: "fieldName",

      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024, // 1M

      // 最多可上传几个文件，默认为 100
      // maxNumberOfFiles: 20,

      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],

      // 将 meta 拼接到 url 参数中，默认 false
      metaWithUrl: false,

      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,

      // 超时时间，默认为 10 秒
      // timeout: 5 * 1000, // 5 秒

      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        console.log("res", res);
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.data);
      },

      // 上传之前触发
      onBeforeUpload(file) {
        // file 选中的文件，格式如 { key: file }
        // console.log('file',file);
        return file;

        // 可以 return
        // 1. return file 或者 new 一个 file ，接下来将上传
        // 2. return false ，不上传这个 file
      },

      // 上传进度的回调函数
      onProgress(progress) {
        // progress 是 0-100 的数字
        // console.log("progress", progress);
      },

      // 单个文件上传成功之后
      onSuccess(file, res) {
        // console.log(`${file.name} 上传成功`, res);
      },

      // 单个文件上传失败
      onFailed(file, res) {
        console.log(`${file.name} 上传失败`, res);
      },

      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res);
      }
    };
  },
  beforeDestroy() {
    // 销毁兄弟传值
    // this.$bus.$off("Addshow");
  }
};
</script>

<style lang="less" scoped></style>
